const keyTypeMap = {
  '': '全部',
  0: '手机钥匙',
  1: '临时钥匙',
  2: '蓝扣钥匙',
  99: '管家钥匙'
}


function getRenterListAndHouseMaster(data) {
  $('.dialog-bg').show()
  $('#goBack').hide()
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo)
      .setRequestUrl('select=house(housenumber,operation(operator_name,operator_mobile,simpleaddr,n_house))&')
      .eqVal('lockid:' + data.lockid)
      .order('lockid'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    $('.popup1').show()
    if (res[0].house.operation.operator_name == 'null') {
      res[0].house.operation.operator_name = '--'
    }
    $('#masterNews').html('').html(`
        <dl>
            <dt>房东姓名</dt>
            <dd>${res[0].house.operation.operator_name || '--'}</div>
        </dl>
        <dl>
            <dt>房东联系方式</dt>
            <dd>${res[0].house.operation.operator_mobile || '--'}</dd>
        </dl>
        <dl>
            <dt>房屋地址</dt>
            <dd class="address-width">${res[0].house.operation.simpleaddr || '--'}</dd>
        </dl>
        <dl>
            <dt>房间号</dt>
            <dd>${res[0].house.housenumber || '--'}</dd>
        </dl>
        <dl>
            <dt>拥有房间总数</dt>
            <dd class="num-width">${res[0].house.operation.n_house || '--'}</dd>
        </dl>
        `)
  }).fail((err) => {
    console.log(err)
  })
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
      .setRequestUrl('select=valid_from,valid_to,user(name,phone,identifier,headpicture)&userrole=neq.255&keytype=in.(0,2)&keystate=is.true&')
      .eqVal('lockid:' + data.lockid)
      .order('valid_from.desc,valid_to.desc,keyid'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    //console.log('当前入住的人员情况', res)
    let text = ''
    let picList = []
    let dom = $('.popups .popup-content2 ').empty();
    $('#subHeaderTxt').html('当前入住的人员情况');
    let $userItems = $('<ul id="userItems"></ul>');
    dom.append($userItems)
    if (res.length != 0) {
      res.forEach(item => {
        item.user = item.user || {
          name: '--',
          identifier: '--',
          phone: '--'
        }
        if (item.user.name == 'null') {
          item.user.name == '--'
        }
        text += `
          <li>
          <div class="popup-avatar" style="background-image:url(${item.user.headpicture})"></div>
            <table width="100%" class="popup-inner-table">
              <tr>
                <th width="64">姓名</th>
                <td>${item.user.name || '--'}</td>
              </tr>
            <tr>
              <th>身份证号</th>
              <td>${item.user.identifier || '--'}</td>
            </tr>
            <tr>
              <th>联系方式</th>
              <td>${item.user.phone || '--'}</td>
            </tr>
            <tr>
              <th>发放时间</th>
              <td>${item.valid_from ? item.valid_from.replace(/T/g, " ") : "--"}</td>
            </tr>
            <tr>
              <th>失效时间</th>
              <td>${item.valid_to ? item.valid_to.replace(/T/g, " ") : "--"}</td>
            </tr>
          </table>
          </li>`

        picList.push(item.user.headpicture)
      })

      $userItems.html(text)
      setTimeout(() => {
        dom[0].scrollTop = 0;
      }, 300)
      picList.forEach((item, index) => {
        var img = new Image();
        img.onload = function () {
          $('.popup-avatar').eq(index).css('backgroundImage', 'url(' + img.src + ')')
        }
        img.src = item;
        img.onerror = function () {
          img.src = 'lib16/img/boy.jpg';
          $('.popup-avatar').eq(index).css('backgroundImage', 'url(' + img.src + ')')
        }
      })
    } else {
      $userItems.html(`<div class="no-pic"><img src="lib16/img/pic_empty.png" alt=""><p>暂无数据</p></div>`)
    }

  }).fail((err) => {
    console.log(err)
  })
}    //一房多人-房东信息，入住人员信息

//更换房客频繁-房东信息，周期内发放的钥匙情况
function KeysIssuedDuringTheCycle(data) {
  $('.dialog-bg').show()
  $('#goBack').hide()
  $('#loadingBox').show();
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo)
      .setRequestUrl('select=house(housenumber,operation(operator_name,operator_mobile,simpleaddr,n_house))&')
      .eqVal('lockid:' + data.lockid)
      .order('lockid'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    //console.log('弹窗', res)
    $('.popup1').show()
    if (res[0].house.operation.operator_name == 'null') {
      res[0].house.operation.operator_name = '--'
    }
    $('#masterNews').html('').html(`
        <dl>
            <dt>房东姓名</dt>
            <dd>${res[0].house.operation.operator_name || '--'}</div>
        </dl>
        <dl>
            <dt>房东联系方式</dt>
            <dd>${res[0].house.operation.operator_mobile || '--'}</dd>
        </dl>
        <dl>
            <dt>房屋地址</dt>
            <dd class="address-width">${res[0].house.operation.simpleaddr || '--'}</dd>
        </dl>
        <dl>
            <dt>房间号</dt>
            <dd>${res[0].house.housenumber || '--'}</dd>
        </dl>
        <dl>
            <dt>拥有房间总数</dt>
            <dd class="num-width">${res[0].house.operation.n_house || '--'}</dd>
        </dl>
        `)
    $('#loadingBox').hide();
  }).fail((err) => {
    $('#loadingBox').hide();
    console.log(err)
  })


  var keyString = ''
  if (data.stats_per_lock_for_formal_last_15day) {
    var keysInfo = data.stats_per_lock_for_formal_last_15day.granted_keys || [];
    keyString = keysInfo.join(',')
  }
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
      .setRequestUrl('select=keyid,account,valid_from,valid_to,user(headpicture,name,identifier,phone),event_summary(tally)&')
      .inVal('keyid:' + keyString)
      .order('valid_from.desc,account'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    //console.log('当前入住的人员情况', res)
    let text = ''
    let picList = []
    let dom = $('.popups .popup-content2 ').empty();
    $('#subHeaderTxt').html('周期内发放的钥匙情况');
    let $userItems = $('<ul id="userItems"></ul>');
    dom.append($userItems)
    if (res.length != 0) {
      res.forEach(item => {
        var tally = 0
        if (item.event_summary && item.event_summary.length != 0) {
          tally = item.event_summary[0].tally
        }
        if(item.user.name == 'null') item.user.name == '--' //牛逼了 这个null就是用户填的字符串
        if(item.user.identifier == 'null') item.user.identifier == '--' //牛逼了 这个null就是用户填的字符串
        text += `
        <li>
          <div class="popup-avatar" style="background-image:url(${item.user.headpicture})"></div>
            <table width="100%" class="popup-inner-table">
              <tr>
                <th width="64">姓名</th>
                <td>${ item.user.name || '--'}</td>
              </tr>
            <tr>
              <th>身份证号</th>
              <td>${item.user.identifier || '--'}</td>
            </tr>
            <tr>
              <th>联系方式</th>
              <td>${item.user.phone || '--'}</td>
            </tr>
            <tr>
              <th>发放时间</th>
              <td>${item.valid_from ? item.valid_from.replace(/T/g, " ") : "--"}</td>
            </tr>
            <tr>
              <th>失效时间</th>
              <td>${item.valid_to ? item.valid_to.replace(/T/g, " ") : "--"}</td>
            </tr>
            <tr class="smaller-tips">
              <th>使用总次数</th>
              <td>${tally}</td>
            </tr>
          </table>
        </li>`
        picList.push(item.user.headpicture)
      });

      $userItems.html(text)
      setTimeout(() => {
        dom[0].scrollTop = 0;
      }, 300)
      picList.forEach((item, index) => {
        var img = new Image();
        img.onload = function () {
          $('.popup-avatar').eq(index).css('backgroundImage', 'url(' + img.src + ')')
        }
        img.src = item;
        img.onerror = function () {
          img.src = 'lib16/img/boy.jpg';
          $('.popup-avatar').eq(index).css('backgroundImage', 'url(' + img.src + ')')
        }
      })
    }
  })
}



//夜间异常活动--详情页'
function getRenterListAndHouseMaster2(data) {
  $('.dialog-bg').show()
  $('#goBack').hide()
  $('#loadingBox').show()
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.keyInfoExpect)
      .setRequestUrl('select=headpicture,name,phone,identifier,detailaddr,housenumber,tally_per_hour_in_night,tally_per_hour_in_dawn&')
      .eqVal('keyid:' + data.keyid),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    // console.log('夜间异常活动--详情页', res)
    res = res || [{}]
    var img = new Image();
    img.onload = function () {
    }
    img.src = (res[0].headpicture) ? res[0].headpicture : 'lib3/img/mrtx.png';
    img.onerror = function () {
      img.src = 'lib3/img/mrtx.png';
    }
    var $img = $(img).addClass('avatar')
    $('.popup3 .avatar').replaceWith($img)

    $('.popup3 .popup-content1-inner').html(`
          <dl class="mr40">
            <div class="avatar-photo" style="background-image:url(${img.src})"></div>
          </dl>
          <dl class="mt5">
            <dt>姓名</dt>
            <dd>${res[0].name || '--'}</dd>
            <dt class="mt8">房屋地址</dt>
            <dd class="address-width">${res[0].detailaddr || '--'}</dd>
          </dl>
          <dl class="mt5">
            <dt>联系方式</dt>
            <dd>${res[0].phone || '--'}</dd>
            <dt class="mt8">房间号</dt>
            <dd>${res[0].housenumber || '--'}</dd>
          </dl>
          <dl class="mt5">
            <dt>身份证号</dt>
            <dd>${res[0].identifier || '--'}</dd>
          </dl>
        `)
    var tally_per_hour_in_night = res[0].tally_per_hour_in_night || {}
    var tally_per_hour_in_dawn = res[0].tally_per_hour_in_dawn || {}
    var nightMap = {20: 0, 21: 0, 22: 0, 23: 0, 0: 0, 1: 0, 2: 0};
    var dawnMap = {
       4: 0, 5: 0, 6: 0
    }
    var tally_per_hour_in_night = res[0].tally_per_hour_in_night || {}
    var tally_per_hour_in_dawn = res[0].tally_per_hour_in_dawn || {}
    var nightMap = [
      tally_per_hour_in_night[20] || 0,
      tally_per_hour_in_night[21] || 0,
      tally_per_hour_in_night[22] || 0,
      tally_per_hour_in_night[23] || 0,
      tally_per_hour_in_night[0] || 0,
      tally_per_hour_in_night[1] || 0,
      tally_per_hour_in_night[2] || 0
    ];
    var dawnMap = {
      4: 0, 5: 0, 6: 0
    }
    for (var key in tally_per_hour_in_dawn) {
      dawnMap[key] = tally_per_hour_in_dawn[key]
    }
    var leftThirtyDayChart = echarts.init(document.getElementById('leftLine'))
    let nightBarOption = {
      title: {
        show: true,
        text: "20:00  —  02:00",
        textStyle: {
          color: "#B4C1C1",
          fontSize: "20",
          fontWeight: "normal"
        },
        left: "40%",
        bottom: "0"
      },
      grid: {
        left: 40,
        top: 10,
        right: 10,
        bottom: 70,
      },
      tooltip: {
        show: true,
        formatter: function (param) {
          try {
            return nightMap[param.dataIndex]
          }catch (e) {
            return 0
          }
        }
      },
      xAxis: {
        type: "category",
        boundaryGap: true,
        data: ["20:00", "21:00", "22:00", "23:00", "24:00", "01:00", "02:00"],
        axisLabel: {
          color: "#B4C0C0",
          fontSize: 12,
          margin: 15,
        },
        splitLine: {
          interval: 1,
          show: true,
          lineStyle: {
            width: 1,
            type: 'dashed',
            color: '#345454',
          }
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: '#819595',
          }
        }
      },
      yAxis: {
        type: "value",
        name: "开门次数(次)",
        max: function (value) {
          return value.max + 2;
        },
        splitLine: {
          show: true,
          lineStyle: {
            width: 1,
            type: 'dashed',
            color: '#345454',
          }
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          color: "#B4C0C0",
          fontSize: 12,
          margin: 10
        }
      },
      color: "rgba(14,240,147,0.4)",
      series: [
        {
          data: nightMap,
          type: "line",
          smooth: true,
          markLine: {
            emphasis: {
              disabled: true
            },
            symbol: ['none', 'none'],
            lineStyle: {
              color: '#345454',
            },
            label: {show: false},
            data: [{xAxis: 0}, {xAxis: 1}, {xAxis: 2}, {xAxis: 3}, {xAxis: 4}, {xAxis: 5}, {xAxis: 6}]
          }
        }
      ]
    };
    leftThirtyDayChart.setOption(nightBarOption)

    var rightThirtyDayChart = echarts.init(document.getElementById('rightLine'))
    let dawnBarOption = {
      title: {
        show: true,
        text: "04:00  —  06:00",
        textStyle: {
          color: "#B4C1C1",
          fontSize: "20",
          fontWeight: "normal"
        },
        left: "40%",
        bottom: "0"
      },
      grid: {
        left: 40,
        top: 10,
        right: 30,
        bottom: 70
      },
      tooltip: {
        show: true,
        formatter: function (param) {
          try {
            return Object.values(dawnMap)[param.dataIndex]
          }catch (e) {
            return 0
          }
        }
      },
      xAxis: {
        type: "category",
        boundaryGap: true,
        data: ["04:00", "05:00", "06:00"],
        axisLabel: {
          color: "#B4C0C0",
          fontSize: 12,
          margin: 15,
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: '#819595',
          }
        }
      },
      yAxis: {
        type: "value",
        name: "开门次数(次)",
        max: function (value) {
          return value.max + 2;
        },
        splitLine: {
          show: true,
          lineStyle: {
            width: 1,
            type: 'dashed',
            color: '#345454',
          }
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          color: "#B4C0C0",
          fontSize: 12,
          margin: 10
        }
      },
      color: "#0095FF",
      series: [
        {
          data: Object.values(dawnMap),
          type: 'line',
          smooth: true,
          markLine: {
            emphasis: {
              disabled: true
            },
            symbol: ['none', 'none'],
            lineStyle: {
              color: '#345454',
            },
            label: {show: false},
            data: [{xAxis: 0}, {xAxis: 1}, {xAxis: 2}]
          }
        }
      ]
    };
    rightThirtyDayChart.setOption(dawnBarOption)
    $('#loadingBox').hide()
    $('.popup3').show()
  }).fail((err) => {
    $('#loadingBox').hide()
    console.log(err)
  })
}

//访客基本情况informationOfVisitors
function informationOfVisitors(data) {
  $('.dialog-bg').show()
  $('#goBack').hide()
  $('#loadingBox').show();
  $('.popup4 #visitorBox4').html(`<div class="loading-box"><img src="./lib3/img/loading.gif" alt=""></div>`)
  var keyString = ''
  if (data.stats_per_lock_for_informal_last_7day) {
    var keysInfo = data.stats_per_lock_for_informal_last_7day.keys || [];
    keyString = keysInfo.join(',')
  }
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
      .setRequestUrl('select=account,valid_from,event_summary(max_opentime),user(key(account))&user.key.userrole=neq.255&user.key.keytype=in.(0,1,2)&user.key.keystate=is.true&')
      .inVal('keyid:' + keyString)
      .order('valid_from.desc,account'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    // console.log('访客基本情况弹窗', res)
    $('.popup4').show()
    var $visitorBox = $('.popup4 #visitorBox');
    var text = ''
    if (res.length != 0) {
      res.forEach(item => {
        var timeString = '--'
        if (item.event_summary.length !== 0) {
          timeString = item.event_summary[0].max_opentime
          timeString = timeString ? timeString.replace(/T/g, "  ") : '--'
        }
        var keyNumber = 0;
        try {
          keyNumber = item.user.key.length
        } catch (err) {
          keyNumber = 0;
        }
        text += `
         <li>
                <i class="visitor-phone-icon"></i>
                <div class="visitor-phone">${item.account}</div>
                <div class="visitor-info">
                  <dl class="give-time">
                    <dt>发放时间</dt><dd>${!item.valid_from ? '--' : item.valid_from.replace(/T/g, "  ")}</dd>
                  </dl>
                  <dl class="give-time">
                    <dt>最近一次使用时间</dt><dd>${timeString}</dd>
                  </dl>
                  <dl>
                    <dt>有效钥匙数量</dt><dd>${keyNumber}</dd>
                  </dl>
                </div>
              </li>
        `
      })
      $visitorBox.html(text)
    } else {
      $visitorBox.html(`<div class="no-pic"><img src="lib16/img/pic_empty.png" alt=""><p>暂无数据</p></div>`)
    }
    setTimeout(() => {
      $visitorBox.scrollTop = 0;
    }, 300)
    $('#loadingBox').hide();
  }).fail((err) => {
    console.log(err)
    $('#loadingBox').hide();
  })
}

//住所频繁更换(一人多处住所人员)左右弹框
function frequentRoomChanger(data, index) {
  $('.dialog-bg').show()
  $('#goBack').hide()
  $('#loadingBox').show();
  // $('.popup2 #personDetaileTitle').html(index === 7 ? `住所频繁更换人员` : '一人多处住所人员')
  // $('.popup2 #houseDetaileTitle').html(index === 7 ? `住所更换房间信息` : '入住房间信息')
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + (index === 7 ? requestApiUrl.personInfo : requestApiUrl.moreAddressInfo))
      .setRequestUrl('select=*&')
      .eqVal('identifier:' + data.identifier),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((response) => {
      // console.log('左弹窗-住所频繁更换人员', response)
      let picList = []
      var res = {};
      if (response && response.length != 0) {
        res = response[0]
      }
      var img = new Image();
      img.crossOrigin = '';
      img.src = (res.headpictures && res.headpictures.length !== 0) ? res.headpictures[0] : 'lib16/img/boy.jpg';
      img.onload = function () {
        $('.popup2 .avatar-photo').css('backgroundImage', `url(${img.src})`)
      }
      // console.log(img)
      img.onerror = function () {
        $('.popup2 .avatar-photo').css('backgroundImage', `url(${img.src})`)
      }

      res.phones = res.phones || [];
      var detailAddr = '--';
      var valid_from = '--';
      var last_open_at = '--';
      var $userItems7 = $('.popup2 #userItems7');
      var text = '';

      if (res.key_details && res.key_details.length !== 0) {
        detailAddr = res.key_details[0].detailaddr || '--';
        valid_from = res.key_details[0].valid_from.replace(/T/g, " ") || '--';
        last_open_at = !res.key_details[0].last_open_at ? '--' : (res.key_details[0].last_open_at.replace(/T/g, " ") || '--');
        res.key_details.forEach((item, index) => {
          var tally = 0
          if (item.event_summary && item.event_summary.length != 0) {
            tally = item.event_summary[0].tally
          }
          text += `<tr role="row" class="odd">
          <td class="addr">
              ${item.detailaddr || '--'}
          </td>
          <td class="digit">${item.housenumber || '--'}</td>
          <td>${keyTypeMap[item.keytype || ''] || '--'}</td>
          <td>${item.valid_from ? item.valid_from.replace(/T/g, " ") : "--"}</td>
          <td>${item.valid_to ? item.valid_to.replace(/T/g, " ") : "--"}</td>
          <td>${item.last_open_at ? item.last_open_at.replace(/T/g, " ") : "--"}</td> </tr>`
        })
      }
      setTimeout(() => {
        $('.popup-content3')[0].scrollTo(0, 0)
      }, 500)
      $userItems7.html(text)

      $('.popup2 #verticalBox7').html(`
          <dl class="mr40">
            <div class="avatar-photo" style="background-image:url(lib16/img/boy.jpg)"></div>
          </dl>
          <dl class="mt5">
            <dt>姓名</dt>
            <dd>${res.name || '--'}</dd>
            <dt class="mt8">入住房间数</dt>
            <dd>${res.tally_houses || '--'}</dd>
          </dl>
          <dl class="mt5">
            <dt>联系方式</dt>
            <dd>${res.phones.join(',') || '--'}</dd>
            <dt class="mt8">最近一次活跃地点</dt>
            <dd class="address-width">${detailAddr}</dd>
          </dl>
          <dl class="mt5">
            <dt>身份证</dt>
            <dd>${res.identifier || '--'}</dd>
            <dt class="mt8">最近一次活跃时间</dt>
            <dd>${last_open_at}</dd>
          </dl>
       `);
      setTimeout(() => {
        $('#loadingBox').hide();
        $('.popup2').show()
      }, 300)

    }
  ).fail((err) => {
    var $userItems7 = $('.popup2 #userItems7');
    $('#loadingBox').hide();
    $userItems7.html('')
  })


}

